package com.cubeofnine.sugar.activity.export_contact;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils.TruncateAt;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.TableLayout.LayoutParams;
import android.widget.TextView;

//import com.cubeofnine.android.api.contact.Address;
import com.cubeofnine.android.api.contact.Contact;
import com.cubeofnine.android.api.contact.ContactList;
import com.cubeofnine.android.api.contact.Email;
//import com.cubeofnine.android.api.contact.IM;
import com.cubeofnine.android.api.contact.Organization;
import com.cubeofnine.android.api.contact.Phone;
import com.cubeofnine.sugar.ActivityImpt;
import com.cubeofnine.sugar.R;
import com.cubeofnine.sugar.inf.HomeInterface;
import com.cubeofnine.sugar.service.element.ErrorValue;
import com.cubeofnine.sugar.service.element.ReturnAddContactList;
import com.cubeofnine.utils.ActivityParams;
import com.cubeofnine.utils.ScrollingTextView;

public class ExportContactsListActivity extends ActivityImpt implements
		HomeInterface {

	private TextView headerText = null;
	private ArrayList<Contact> contacts = new ArrayList<Contact>();

	public String getClassName() {
		return ExportContactsListActivity.class.getName();
	}

	public void onCreate(Bundle savedInstanceState) {
		Log.i(getClassName(), "onCreate() : Start");

		super.onCreate(savedInstanceState);
		setContentView(R.layout.phone_contacts);

		headerText = (TextView) findViewById(R.id.header_title);

		initProgressDialog(null);
		Thread thread = new ExportContactsListThread(this);
		thread.start();

		Log.i(getClassName(), "onCreate() : End");
	}

	public void onStart() {
		Log.i(getClassName(), "onStart() : Start");

		super.onStart();

		headerText.setText(R.string.function_export_contacts);

		Thread thread = (Thread) getLastNonConfigurationInstance();
		if (thread != null && thread.isAlive()) {
			initProgressDialog(null);
		}

		Log.i(getClassName(), "onStart() : End");
	}

	public void onDestroy() {
		Log.i(getClassName(), "onDestroy() : Start");

		if (dialog != null && dialog.isShowing()) {
			dialog.dismiss();
			dialog = null;
		}

		Log.i(getClassName(), "onDestroy() : End");
		super.onDestroy();
	}

	public void onBackPressed() {
		Log.i(getClassName(), "onBackPressed() : Start");

		Thread thread = (Thread) getLastNonConfigurationInstance();
		if (thread == null || !thread.isAlive()) {
			super.onBackPressed();
		}

		Log.i(getClassName(), "onBackPressed() : End");
	}

	public void initialProcess(ContactList contactList, String message) {
		Log.i(getClassName(), "initialProcess() : Start");

		try {
			if (message == null || message.isEmpty()) {
				if (contactList != null) {
					ArrayList<Contact> contacts = contactList.getContacts();
					Log.d(getClassName(), "contactCount = " + contacts.size());

					if (contacts != null && !contacts.isEmpty()) {
						LinearLayout root = (LinearLayout) findViewById(R.id.body_root_linear_layout);
						root.removeAllViewsInLayout();

						Iterator<Contact> contactIter = null;
						Contact contact = null;

						String id = null;
						String displayName = null;

						ArrayList<Phone> phones = null;
						// Iterator<Phone> phoneIter = null;
						// Phone phone = null;
						// String phoneNumber = null;
						// String phoneType = null;
						// String phoneLabel = null;

						ArrayList<Email> emails = null;
						// Iterator<Email> emailIter = null;
						// Email email = null;
						// String emailAddress = null;
						// String emailType = null;
						// String emailLabel = null;

						// ArrayList<Address> addresses = null;
						// Iterator<Address> addressIter = null;
						// Address address = null;
						// String fullAddress = null;
						// String addressLabel = null;

						// ArrayList<IM> ims = null;
						// Iterator<IM> imIter = null;
						// IM im = null;
						// String imName = null;
						// String imType = null;
						// String imLabel = null;

						ArrayList<Organization> organizations = null;
						Iterator<Organization> organizationIter = null;
						Organization organization = null;
						String companyName = null;
						String jobTitle = null;
						String organizationType = null;
						String organizationLabel = null;

						LinearLayout contactLayout = null;
						LinearLayout textGroupLayout = null;
						ScrollingTextView textView = null;
						CheckBox checkBox = null;

						// Contact Root Layout
						LinearLayout.LayoutParams contactLayoutParams = new LinearLayout.LayoutParams(
								LayoutParams.MATCH_PARENT,
								LayoutParams.WRAP_CONTENT);// W,H
						contactLayoutParams.setMargins(10, 2, 10, 2);// left,
																		// top,
																		// right,
																		// bottom
						LinearLayout.LayoutParams textGroupLayoutParams = new LinearLayout.LayoutParams(
								LayoutParams.MATCH_PARENT,
								LayoutParams.WRAP_CONTENT);// W,H
						textGroupLayoutParams.setMargins(5, 0, 0, 0);// left,
																		// top,
																		// right,
																		// bottom

						LinearLayout.LayoutParams textViewParams = new LinearLayout.LayoutParams(
								LayoutParams.FILL_PARENT,
								LayoutParams.WRAP_CONTENT);
						// textViewParams.setMargins(0, 2, 0, 2);

						boolean isHavePhoneNo = false;
						boolean isHaveEmailAddress = false;
						boolean isHaveOrganization = false;

						Collections.sort(contacts);
						contactIter = contacts.iterator();
						while (contactIter.hasNext()) {
							contact = contactIter.next();

							// initial variable
							{
								isHavePhoneNo = false;
								isHaveEmailAddress = false;
								isHaveOrganization = false;

								id = null;
								displayName = null;

								// phoneNumber = null;
								// phoneType = null;
								// phoneLabel = null;
								//
								// emailAddress = null;
								// emailType = null;
								// emailLabel = null;

								// fullAddress = null;
								// addressLabel = null;

								// imName = null;
								// imType = null;
								// imLabel = null;

								companyName = null;
								jobTitle = null;
								organizationType = null;
								organizationLabel = null;
							}

							id = contact.getId();
							displayName = contact.getDisplayName();

							Log.d(getClassName(), "id = " + id);
							Log.d(getClassName(), "displayName = "
									+ displayName);

							phones = contact.getPhone();
							if (phones != null && !phones.isEmpty()) {
								isHavePhoneNo = true;

								// phoneIter = phones.iterator();
								// while (phoneIter.hasNext()) {
								// phone = phoneIter.next();
								// phoneNumber = phone.getNumber();
								// phoneType = phone.getType();
								// phoneLabel = phone.getLabel();
								//
								// Log.d(getClassName(), "phoneNumber = "
								// + phoneNumber);
								// Log.d(getClassName(), "phoneType = "
								// + phoneType);
								// Log.d(getClassName(), "phoneLabel = "
								// + phoneLabel);
								// }
							}

							emails = contact.getEmail();
							if (emails != null && !emails.isEmpty()) {
								isHaveEmailAddress = true;

								// emailIter = emails.iterator();
								// while (emailIter.hasNext()) {
								// email = emailIter.next();
								// emailAddress = email.getAddress();
								// emailType = email.getType();
								// emailLabel = email.getLabel();
								//
								// Log.d(getClassName(), "emailAddress = "
								// + emailAddress);
								// Log.d(getClassName(), "emailType = "
								// + emailType);
								// Log.d(getClassName(), "emailLabel = "
								// + emailLabel);
								// }
							}

							// addresses = contact.getAddresses();
							// if (addresses != null && !addresses.isEmpty()) {
							// addressIter = addresses.iterator();
							// while (addressIter.hasNext()) {
							// address = addressIter.next();
							// fullAddress = address.toString();
							// addressLabel = address.getLabel();
							//
							// Log.d(getClassName(), "fullAddress = "
							// + fullAddress);
							// Log.d(getClassName(), "addressLabel = "
							// + addressLabel);
							// }
							// }

							// ims = contact.getImAddresses();
							// if (ims != null && !ims.isEmpty()) {
							// imIter = ims.iterator();
							// while (imIter.hasNext()) {
							// im = imIter.next();
							// imName = im.getName();
							// imType = im.getType();
							// imLabel = im.getLabel();
							//
							// Log.d(getClassName(), "imName = " + imName);
							// Log.d(getClassName(), "imType = " + imType);
							// Log.d(getClassName(), "imLabel = "
							// + imLabel);
							// }
							// }

							organizations = contact.getOrganization();
							if (organizations != null
									&& !organizations.isEmpty()) {
								isHaveOrganization = true;

								organizationIter = organizations.iterator();
								while (organizationIter.hasNext()) {
									organization = organizationIter.next();
									companyName = organization
											.getOrganization();
									jobTitle = organization.getTitle();
									organizationType = organization.getType();
									organizationLabel = organization.getLabel();

									Log.d(getClassName(), "companyName = "
											+ companyName);
									Log.d(getClassName(), "jobTitle = "
											+ jobTitle);
									Log.d(getClassName(), "organizationType = "
											+ organizationType);
									Log.d(getClassName(),
											"organizationLabel = "
													+ organizationLabel);

									break;
								}
							}

							// Have any one Phone No.
							// Have any one Email
							// Have any one Organization
							if (isHavePhoneNo && isHaveEmailAddress
									&& isHaveOrganization) {
								// Contact Usage.
								this.contacts.add(contact);

								// Create Group Contact
								contactLayout = new LinearLayout(this);
								contactLayout
										.setLayoutParams(contactLayoutParams);
								contactLayout
										.setOrientation(LinearLayout.HORIZONTAL);

								// Check Box
								checkBox = new CheckBox(this);
								checkBox.setId(Integer.parseInt(id, 10));
								checkBox.setOnClickListener(new OnClickCheckSame(
										this));
								contactLayout.addView(checkBox);

								// Text Layout
								textGroupLayout = new LinearLayout(this);
								textGroupLayout
										.setLayoutParams(textGroupLayoutParams);
								textGroupLayout
										.setOrientation(LinearLayout.VERTICAL);
								textGroupLayout.setGravity(Gravity.CENTER);

								{
									// Contact Name
									textView = new ScrollingTextView(this);
									textView.setLayoutParams(textViewParams);
									textView.setText(displayName);
									textView.setTextColor(Color
											.rgb(0, 102, 255));// Blue
									textView.setTextAppearance(this,
											android.R.attr.textAppearanceLarge);
									textView.setSingleLine(true);
									textView.setHorizontallyScrolling(true);
									textView.setEllipsize(TruncateAt.MARQUEE);
									textView.setMarqueeRepeatLimit(1);
									textView.setMovementMethod(new ScrollingMovementMethod());

									textView.setOnClickListener(new OnClickViewPhoneContactDetail(
											this, id, displayName));

									textGroupLayout.addView(textView);

									// JobTitle Title
									if (jobTitle == null || jobTitle.isEmpty()) {
										jobTitle = "";
									}

									textView = new ScrollingTextView(this);
									textView.setLayoutParams(textViewParams);
									textView.setText("Job Title : " + jobTitle);
									textView.setTextColor(Color.rgb(170, 170,
											170));// Gray
									textView.setTextAppearance(this,
											android.R.attr.textAppearanceSmall);
									textView.setSingleLine(true);
									textView.setHorizontallyScrolling(true);
									textView.setEllipsize(TruncateAt.MARQUEE);
									textView.setMarqueeRepeatLimit(1);
									textView.setMovementMethod(new ScrollingMovementMethod());
									textGroupLayout.addView(textView);

									// Company
									if (companyName != null
											&& !companyName.isEmpty()) {
										textView = new ScrollingTextView(this);
										textView.setLayoutParams(textViewParams);
										textView.setText("Company : "
												+ companyName);
										textView.setTextColor(Color.rgb(170,
												170, 170));// Gray
										textView.setTextAppearance(
												this,
												android.R.attr.textAppearanceSmall);
										textView.setSingleLine(true);
										textView.setHorizontallyScrolling(true);
										textView.setEllipsize(TruncateAt.MARQUEE);
										textView.setMarqueeRepeatLimit(1);
										textView.setMovementMethod(new ScrollingMovementMethod());
										textGroupLayout.addView(textView);
									}
								}

								contactLayout.addView(textGroupLayout);
								root.addView(contactLayout);
							}
						}
					}
				}
			} else {
				alertMessage(message, true);
			}

			if (dialog != null && dialog.isShowing()) {
				dialog.dismiss();
				dialog = null;
			}
		} catch (Exception e) {
			Log.e(getClassName(), "Error", e);
		}

		Log.i(getClassName(), "initialProcess() : End");
	}

	public void onClickCheckAll(View view) {
		Log.i(getClassName(), "onClickCheckAll() : Start");

		if (this.contacts != null && !this.contacts.isEmpty()) {
			CheckBox checkBox = (CheckBox) view;
			boolean checked = checkBox.isChecked();

			Iterator<Contact> contactIter = this.contacts.iterator();
			Contact contact = null;
			while (contactIter.hasNext()) {
				contact = contactIter.next();
				checkBox = (CheckBox) findViewById(Integer.parseInt(
						contact.getId(), 10));
				checkBox.setChecked(checked);
			}
		}

		Log.i(getClassName(), "onClickCheckAll() : End");
	}

	public void onClickCheckSame(View view) {
		Log.i(getClassName(), "onClickCheckSame() : Start");

		if (this.contacts != null && !this.contacts.isEmpty()) {
			CheckBox checkBox = null;
			Iterator<Contact> contactIter = this.contacts.iterator();
			Contact contact = null;
			boolean checked = true;
			while (contactIter.hasNext()) {
				contact = contactIter.next();
				checkBox = (CheckBox) findViewById(Integer.parseInt(
						contact.getId(), 10));
				if (!checkBox.isChecked()) {
					checked = false;
					break;
				}
			}

			checkBox = (CheckBox) findViewById(R.id.check_all);
			checkBox.setChecked(checked);
		}

		Log.i(getClassName(), "onClickCheckSame() : End");
	}

	public void onClickSync(View view) {
		Log.i(getClassName(), "onClickSync() : Start");
		view.startAnimation(AnimationUtils.loadAnimation(this,
				R.anim.image_click));

		if (this.contacts != null && !this.contacts.isEmpty()) {
			ArrayList<Contact> selectedItem = new ArrayList<Contact>();

			CheckBox checkBox = null;
			Iterator<Contact> contactIter = this.contacts.iterator();
			Contact contact = null;
			while (contactIter.hasNext()) {
				contact = contactIter.next();
				checkBox = (CheckBox) findViewById(Integer.parseInt(
						contact.getId(), 10));
				if (checkBox.isChecked()) {
					selectedItem.add(contact);
				}
			}

			if (selectedItem.isEmpty()) {
				alertDialog("Please select at least one item.");
			} else {
				AlertDialog.Builder adb = new AlertDialog.Builder(this);

				adb.setIcon(android.R.drawable.ic_dialog_alert);
				adb.setTitle(R.string.function_export_contacts);
				adb.setMessage(R.string.msg_want_to_continue);
				adb.setPositiveButton(R.string.button_yes,
						new OnClickDialogToContinue(this, selectedItem, true));
				adb.setNegativeButton(R.string.button_no,
						new OnClickDialogToContinue(this, selectedItem, false));
				adb.show();
			}
		} else {
			alertDialog("Please select at least one item.");
		}

		Log.i(getClassName(), "onClickSync() : End");
	}

	public void gotoNextProcess(ArrayList<Contact> selectedItem, boolean answer) {
		Log.i(getClassName(), "gotoNextProcess() : Start");
		Log.d(getClassName(), "answer = " + answer);

		if (answer) {
			initProgressDialog(null);

			Thread thread = (Thread) getLastNonConfigurationInstance();
			if (thread == null || !thread.isAlive()) {
				thread = new SyncUpContactsListThread(this, selectedItem);
				thread.start();
			}
		}

		Log.i(getClassName(), "gotoNextProcess() : End");
	}

	public void resultSyncProcess(ReturnAddContactList result,
			String errorMessage) {
		Log.i(getClassName(), "resultSyncProcess() : String");
		Log.d(getClassName(), "errorMessage = " + errorMessage);

		if (errorMessage != null && !"".equals(errorMessage.trim())) {
			alertDialog(errorMessage);
		} else {
			ErrorValue error = result.getError();
			if (error != null && error.getNumber() != 0) {
				alertDialog(error.getDescription());
			} else {
				int inserted = result.getInsert_contact();
				int duplicate = result.getDuplicate_contact();
				int total = result.getTotal_contact();

				String message = "Selected Items : " + total + "\n"//
						+ "Success Items : " + inserted + "\n" //
						+ "Duplicate Items : " + duplicate + "\n" //
						+ "Fail Items : " + (total - inserted - duplicate);

				AlertDialog.Builder adb = new AlertDialog.Builder(this);

				adb.setIcon(android.R.drawable.ic_dialog_alert);
				adb.setTitle(R.string.function_export_contacts);
				adb.setMessage(message);
				adb.setPositiveButton(R.string.button_ok,
						new OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								// TODO Auto-generated method stub
							}
						});
				adb.show();
			}
		}

		dialog.dismiss();
		Log.i(getClassName(), "resultSyncProcess() : End");
	}

	public void gotoPhoneContactDetail(View view, String id, String name) {
		Log.i(getClassName(), "gotoPhoneContactDetail() : Start");
		view.startAnimation(AnimationUtils.loadAnimation(this,
				R.anim.image_click));

		List<ActivityParams> params = new Vector<ActivityParams>();
		params.add(new ActivityParams("CONTACT_ID", id));
		params.add(new ActivityParams("CONTACT_NAME", name));

		gotoActivity(PhoneContactDetailActivity.class, params);

		Log.i(getClassName(), "gotoPhoneContactDetail() : End");
	}

	public void onClickHomeButton(View view) {
		try {
			view.startAnimation(AnimationUtils.loadAnimation(this,
					R.anim.image_click));
			createMenuPopup(R.string.label_home_menu, new String[] {
					MENU_IMPORT_CONTACT, MENU_LOGOUT });
		} catch (Exception e) {
			Log.e(ActivityImpt.class.getName(), "Error", e);
		}
	}
}
